package com.serverlite.framework.dao;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.serverlite.framework.utils.PropertiesUtils;

public class C3P0 {
    private static C3P0 dbPool;
    private ComboPooledDataSource dataSource;

    private C3P0() {
        try {
            dataSource = new ComboPooledDataSource();
            dataSource.setUser(PropertiesUtils.get("jdbc.username"));
            dataSource.setPassword(PropertiesUtils.get("jdbc.password"));
            dataSource.setJdbcUrl(PropertiesUtils.get("jdbc.url"));
            dataSource.setDriverClass(PropertiesUtils.get("jdbc.driver"));
            dataSource.setInitialPoolSize(Integer.valueOf(PropertiesUtils
                    .get("initialPoolSize")));
            dataSource.setMinPoolSize(Integer.valueOf(PropertiesUtils
                    .get("minPoolSize")));
            dataSource.setMaxPoolSize(Integer.valueOf(PropertiesUtils
                    .get("maxPoolSize")));
            dataSource.setMaxStatements(Integer.valueOf(PropertiesUtils
                    .get("maxStatements")));
            dataSource.setMaxIdleTime(Integer.valueOf(PropertiesUtils
                    .get("maxIdleTime")));
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }

    public final static C3P0 getInstance() {
        if (dbPool == null) {
            dbPool = new C3P0();
        }
        return dbPool;
    }

    public final Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("can not get connection!", e);
        }
    }

    public void printLog(Connection conn) throws SQLException {
        int numConnections = dataSource.getNumConnections();
        int numBusyConnections = dataSource.getNumBusyConnections();
        int numIdleConnections = dataSource.getNumIdleConnections();
        int numActiveThreads = dataSource.getThreadPoolNumActiveThreads();
        int numIdleThreads = dataSource.getThreadPoolNumIdleThreads();
        int numTasksPending = dataSource.getThreadPoolNumTasksPending();
        int poolSize = dataSource.getThreadPoolSize();
        System.out.println("ThreadPool:" + " poolSize " + poolSize
                + ", numActiveThreads " + numActiveThreads
                + ", numIdleThreads " + numIdleThreads + ", numTasksPending "
                + numTasksPending);
        System.out.println("ConnectionPool:" + " numConnections "
                + numConnections + ", numBusyConnections " + numBusyConnections
                + ", numIdleConnections " + numIdleConnections
                + ", conn.isClosed " + conn.isClosed());
    }
}